package com.changpay.zywy.ui.activity.machinecontrol

import android.content.Intent
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.changpay.zywy.R
import com.changpay.zywy.base.BaseActivity
import com.changpay.zywy.base.IView
import com.changpay.zywy.ext.showToast
import com.changpay.zywy.ext.sss
import com.changpay.zywy.http.RetrofitHelper
import com.changpay.zywy.ui.activity.loan.LoanSecondActivity
import com.changpay.zywy.ui.activity.serivce.SelectProduceActivity
import com.changpay.zywy.ui.activity.serivce.SelectSnCodeActivity
import com.changpay.zywy.utils.DialogUtil
import kotlinx.android.synthetic.main.activity_allow.*
import kotlinx.android.synthetic.main.activity_allow.tv_project_name
import kotlinx.android.synthetic.main.activity_loan_first.*
import kotlinx.android.synthetic.main.title_layout.*
import java.util.*


class AllowActivity : BaseActivity(), IView {
    private var gc_id: String = ""
    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this, "操作中")
    }
    private var member_id = ""  // 调拨用户id
    private var produce_id = ""  // 调拨产品id
    private var sn_code = "" // 调拨sn_code

    private var type_jisuan: Int = 0  // 是分期还是不分期
    private var type_fenqishu: Int = 3  // 分期的月份数
    private var type_hasJieSUAN: Int = 0 // 是否拥有结算选项


    private val onClickListener = View.OnClickListener { view ->
        when (view.id) {

            R.id.tv_back_name -> Intent(this, SelectAllowPeopleActivity::class.java).run {
                startActivityForResult(this, 100)
            }
            R.id.tv_produce -> {
                if (gc_id.isEmpty()) {
                    showToast("请先选择项目名称")
                    return@OnClickListener
                }
                Intent(this, SelectProduceActivity::class.java).run {
                    putExtra("member_id", "") // 默认为自己
                    putExtra("gc_id", gc_id)
                    putExtra("type", 3)
                    startActivityForResult(this, 100)
                }
            }
            R.id.tv_sn_number -> {
                if (produce_id.isEmpty()) {
                    showToast("选择调拨的产品")
                    return@OnClickListener
                }
                Intent(this, SelectSnCodeActivity::class.java).run {
                    putExtra("title", "选择调拨产品的SN号")
                    putExtra("goods_id", produce_id)
                    putExtra("machine_type", "1") //   1 未激活的 2 激活
                    putExtra("type", "allow")
                    startActivityForResult(this, 100)
                }
            }
            R.id.tv_project_name ->
                Intent(this, LoanSecondActivity::class.java).run {
                    startActivityForResult(this, 100)
                }

            R.id.tv_apply -> submit()
        }
    }

    override fun attachLayoutRes(): Int {
        return R.layout.activity_allow
    }

    override fun showLoading() {
        mDialog.show()

    }

    override fun hideLoading() {
        mDialog.dismiss()

    }

    override fun showDefaultMsg(msg: String) {
        showToast(msg)
    }

    override fun showMsg(msg: String) {
        showToast(msg)
    }

    override fun showError(errorMsg: String) {
        showToast(errorMsg)
    }


    override fun initData() {
    }

    override fun initView() {
        tv_title.text = "发起调拨"
        iv_back.setOnClickListener { finish() }
        tv_back_name.setOnClickListener(onClickListener)
        tv_produce.setOnClickListener(onClickListener)
        tv_sn_number.setOnClickListener(onClickListener)
        tv_apply.setOnClickListener(onClickListener)
        tv_project_name.setOnClickListener(onClickListener)
        rg_jiezhang.setOnCheckedChangeListener { group, checkedId ->
            if (checkedId == R.id.rb_quankuan) {
                type_jisuan = 0
                ll_select_fenqi.visibility = View.GONE
            } else {
                type_jisuan = 1
                ll_select_fenqi.visibility = View.VISIBLE
            }
        }
        rg_fenqitype.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_one -> type_fenqishu = 3
                R.id.rb_two -> type_fenqishu = 6
                R.id.rb_three -> type_fenqishu = 9
                R.id.rb_four -> type_fenqishu = 12
            }
            tv_fenqishu.text = type_fenqishu.toString()

            // 判断是否有单价
            val danjia = et_jiju_danjia.text.toString()
            if (!(danjia.isNullOrEmpty())) {
                tv_fenqidanjia.text =String.format("%.2f",(tv_jiju_zhongjia.text.toString().toFloat() / type_fenqishu))
            } else {
                tv_fenqidanjia.text = "0.00"
            }
        }


        et_jiju_danjia.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                val text = s.toString()
                if (text.isNullOrEmpty()) {
                    tv_jiju_zhongjia.text = ""
                } else {
                    val shuliang = tv_shuliang.text.toString().toInt()
                    tv_jiju_zhongjia.text = (text.toInt() * shuliang).toString()
                    tv_fenqidanjia.text =String.format("%.2f",(tv_jiju_zhongjia.text.toString().toFloat() / type_fenqishu))
                }
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }
        })

    }

    override fun start() {

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)



        when (resultCode) {
            200 -> {
                member_id = data?.getStringExtra("member_id").toString()
                tv_back_name.text = data?.getStringExtra("member_name").toString()
                tv_phone.text = data?.getStringExtra("member_mobile").toString()
                if (data?.getStringExtra("show_bill") == "0") {
                    type_hasJieSUAN = 0
                    rg_jiezhang.visibility = View.GONE
                    ll_jijudanjia.visibility = View.GONE
                    ll_jijuzhongja.visibility = View.GONE
                    ll_select_fenqi.visibility = View.GONE
                } else {
                    type_hasJieSUAN = 1
                    rg_jiezhang.visibility = View.VISIBLE
                    ll_jijudanjia.visibility = View.VISIBLE
                    ll_jijuzhongja.visibility = View.VISIBLE

                    if (type_jisuan == 0) {
                        ll_select_fenqi.visibility = View.GONE
                    }else
                    {
                        ll_select_fenqi.visibility = View.VISIBLE
                    }
                }

            }
            300 -> {
                sn_code = ""
                tv_sn_number.text = ""
                tv_shuliang.text = ""
                produce_id = data?.getStringExtra("produce_id").toString()
                tv_produce.text = data?.getStringExtra("produce_name").toString()
            }

            400 -> {
                tv_shuliang.text = data?.getStringExtra("number").toString()
                tv_sn_number.text = data?.getStringExtra("sn_show").toString()
                sn_code = data?.getStringExtra("sn_code").toString()

                // 判断是否有填入单价,有的话算出总价
                val danjia = et_jiju_danjia.text.toString()
                if (!(danjia.isNullOrEmpty())) {
                    val danjiaint = danjia.toInt()
                    val shuliang = tv_shuliang.text.toString().toInt()
                    tv_jiju_zhongjia.text = (danjiaint * shuliang).toString()
                }
            }
            500 -> {
                tv_project_name.text = data?.getStringExtra("gc_name")
                gc_id = data!!.getStringExtra("gc_id")
            }
        }


    }

    private fun submit() {

        if (TextUtils.isEmpty(produce_id)) {
            showToast("请先选择调拨产品")
            return
        }

        if (TextUtils.isEmpty(sn_code)) {
            showToast("请先选择SN号")
            return
        }

        val name = tv_back_name.getText().toString()
        val member_mobile = tv_phone.text.toString()
        val number = tv_shuliang.text.toString()
        if (TextUtils.isEmpty(name)) {
            showToast("请先输入伙伴姓名")
            return
        }
        if (TextUtils.isEmpty(member_mobile)) {
            showToast("请先输入伙伴手机号")
            return
        }

        val params = HashMap<String, String>()
        // 1.判断是否需要显示结算
        if (type_hasJieSUAN == 1) {
            //先判断是否有填入单价和总价
            val danjia = et_jiju_danjia.text.toString()
            val zhongjia = tv_jiju_zhongjia.text


            // 为空时，先填入单价
            if (danjia.isNullOrEmpty() || zhongjia.isNullOrEmpty()) {
                showToast("请先填入单价")

            } else {
                if (type_jisuan == 0)  // 不分期
                {
                    params["type"] = "1"
                    params["unit_price"] = danjia
                } else if (type_jisuan == 1)  // 分期
                {
                    params["type"] = "2"
                    params["period_num"] = type_fenqishu.toString()
                    params["unit_price"] = danjia
                }
            }
        }
        params["key"] = token
        params["goods_id"] = produce_id
        params["sn_code"] = sn_code
        params["member_name"] = name
        params["member_mobile"] = member_mobile
        params["num"] = number
        RetrofitHelper.service.initiateATransferNew(params).sss(this)
        {
            showToast(it.result.toString())
            finish()
        }
    }

}
